package com.you.raft.core.impl;

import com.you.raft.common.entity.Command;
import com.you.raft.common.entity.LogEntry;
import com.you.raft.core.StateMachine;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 状态机:使用一个哈希表模拟K-V键值对数据库
 */
@Slf4j
public class DefaultStateMachine implements StateMachine {
    private Map<String, String> machineDB = new ConcurrentHashMap<>();

    public static StateMachine getInstance() {
        return DefaultStateMachineLazyHolder.INSTANCE;
    }

    private static class DefaultStateMachineLazyHolder {
        private static DefaultStateMachine INSTANCE = new DefaultStateMachine();
    }

    @Override
    public synchronized void apply(LogEntry logEntry) {
        Command command = logEntry.getCommand();
        if (command == null) {
            log.info("跳过no-op日志");
            return;
        }
        String key = command.getKey();
        String value = command.getValue();
        put(key, value);
    }

    @Override
    public String get(String key) {
        return machineDB.get(key);
    }

    @Override
    public void put(String key, String value) {
        machineDB.put(key, value);
    }

    @Override
    public void del(String key) {
        machineDB.remove(key);
    }
}
